#include "Stdafx.h"

#include "Helper.h"

#include <msclr/marshal.h>        // .NET string to C-style string
#include <msclr/marshal_cppstd.h> // .NET string to STL string
#include <string>

using namespace std;

using namespace System;
using namespace System::Runtime;
using namespace System::Runtime::InteropServices;
using namespace System::Runtime::CompilerServices;

using namespace msclr::interop;

std::string NetStringToString( System::String^ net_s )
{
	marshal_context^ context = gcnew marshal_context();
	const char* c_s = context->marshal_as<const char*>(net_s);
	std::string str(c_s);
	return str;
}

std::string GetErrorText( bool bLst, DWORD errcode /* = 0 */ )
{
	LPSTR lpMsgBuf;
	if(bLst)
	{
		DWORD nRet = FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, GetLastError(), MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPSTR)&lpMsgBuf, 0, NULL);
		if( !nRet )
			return GetErrorText(true);
	}
	else
	{
		DWORD nRet = FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, errcode, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPSTR)&lpMsgBuf, 0, NULL);
		if( !nRet )
			return GetErrorText(true);
	}
	std::string ret = lpMsgBuf;
	LocalFree(lpMsgBuf);
	return ret;
}